/**
 * Created by Administrator on 2017/10/20.
 */
public class LinkedList implements LinearList {
    private Node head;
    public LinkedList() {
        this.head = new Node();
    }

    @Override
    public int length() {
        int length=0;
        Node p=head.getNext();
        while (p!=null){
            length++;
            p=p.getNext();
        }
        return length;
    }

    @Override
    public int search(Object element) {
        Node p=head.getNext();
        int k=0;
        while(p!=null&&!p.getData().equals(element))
        {
            p=p.getNext();
            k++;
        }
        if (p!=null)
            return k;
        return -1;
    }

    @Override
    public Object getElementAt(int index) throws Exception {
        if (index<0||index>length()) throw new Exception("下标越界");
        Node p=head.getNext();
        int k=0;
        while (p!=null&& k<index)
        {
            p=p.getNext();
            k++;
        }
        return p;
    }

    @Override
    public void insert(int index, Object element) throws Exception {
        Node p=head;
        int k=0;
        if (index<0||index>length()) throw new Exception("下标不存在");
        while (k<index)
        {
            p=p.getNext();
            k++;
        }
        Node newNode=new Node(element);
        newNode.setNext(p.getNext());
        p.setNext(newNode);
    }

    @Override
    public Object remove(int index) throws Exception {
        Node p=head;
        int k=-1;
        if (index<0||index>length()) throw new Exception("下标不存在");
        while (k<index)
        {
            p=p.getNext();
            k++;
        }
        Node t=p.getNext();
        p.setNext(t.getNext());
        t.setNext(null);
        return t;
    }

    @Override
    public boolean isEmpty() {
        return head.getNext()==null;
    }

    @Override
    public boolean isFull() {
        return false;
    }

    @Override
    public void clear() {
        head.setNext(null);

    }

    @Override
    public void showList() {
        Node p=head.getNext();
        while(p!=null){
            System.out.print(p.getData()+",");
            p=p.getNext();
        }
    }
}
